<script setup lang="ts">
import {computed, onMounted, ref, watch} from "vue";
import {Search, ShoppingCart} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";
import {useUserStore} from "@/stores/userStore";
import {
  getAllShopGenres,
  getGoodsListByGenre,
  goodsLists,
  hottestGoods,
  searchGoods,
  searchGoodsByName
} from "@/router/api";
import {authUtilStore} from "@/utils/authStore";
import {useRouter} from "vue-router";
import {useCartStore} from "@/stores/cartStore";

// 添加一个抑制watch的标志
const suppressWatch = ref(false);
const cartStore = useCartStore()
const authStore = authUtilStore();
const pageSize = ref(15); // 分页大小
const currentPage = ref(1); // 商品列表当前页码
const total = ref(75); // 商品1总条数
const currentPage1 = ref(1); // 搜索结果当前页码
const total1 = ref(75); // 搜索结果总条数
const currentPage2 = ref(1); // 类型商品当前页码
const total2 = ref(75); // 类型商品总条数
const userInfo = useUserStore().userInfo;// 用户信息
const isLogin = computed(() => useUserStore().isLogin);//是否登录
const input = ref("");//搜索框内容
const value = ref("");//类型选择
const cities = ref<{ value: string; label: string }[]>([]);//类型
const goodsList = ref<Array<{
  id: number;
  name: string;
  image: string;
  sale_price: number;
  market_price: number;
}>>([]);
const hottestGoodsList = ref<Array<{
  id: number;
  name: string;
  image: string;
  sale_price: number;
  market_price: number;
}>>([]);
const mapData = (data: Array<any>) => {
  return data.map((item) => ({
    id: item.id,
    name: item.name,
    image: item.image,
    sale_price: item.sale_price,
    market_price: item.market_price,
  }));
};
const showMessage = (type: any, message: any) => {// 显示消息提示
  ElMessage({
    type,
    message,
    duration: 1000,
  });
};
const getGoodsList = async () => {
  try {
    const page = (currentPage.value - 1) * pageSize.value;
    const response: any = await goodsLists(page, pageSize.value);
    goodsList.value = mapData(response.goodsList);
    total.value = response.totals;
  } catch {
    showMessage("error", "获取商品列表失败");
  }
}
const getHottestGoodsList = async () => {
  try {
    const response = await hottestGoods();
    if (Array.isArray(response))
      hottestGoodsList.value = mapData(response);
  } catch {
    showMessage("error", "获取热销商品列表失败");
  }
}
//获取所有商品类型
const fetchGenres = async () => {
  try {
    const response = await getAllShopGenres();
    if (Array.isArray(response)) {
      cities.value = response.map((genre: any) => ({
        value: genre.name,
        label: genre.name,
        category_id: genre.id,
      }));
    }
  } catch (error) {
    showMessage('error', '获取商品类型失败！');
  }
};
// 根据类型获取商品列表
const fetchDataByGenre = async () => {
  if (value.value.trim() === '') {
    await getGoodsList();
  } else {
    try {
      const page = (currentPage2.value - 1) * pageSize.value;
      const response: any = await getGoodsListByGenre(value.value, page, pageSize.value);
      goodsList.value = mapData(response.goodsList);
      total2.value = response.totals;
      input.value = '';
    } catch (error) {
      showMessage('error', '获取失败！');
    }
  }
};
// 取消选择
const handleClear = () => {
  value.value = '';
  showMessage('info', '已取消选择！');
};
// 搜索商品
const searchData = async () => {
  if (input.value.trim() === '') {
    suppressWatch.value = true; // 禁止watch触发
    value.value = '';
    await getGoodsList();
  } else {
    try {
      const page = (currentPage1.value - 1) * pageSize.value;
      const response: any = await searchGoods(input.value, page, pageSize.value);
      goodsList.value = mapData(response.goodsList);
      total1.value = response.totals;
      suppressWatch.value = true; // 禁止watch触发
      value.value = '';
    } catch (error) {
      showMessage('error', '搜索失败！');
    }
  }
};
watch(value, () => {
  if (suppressWatch.value) {
    suppressWatch.value = false; // 重置标志
    return;
  }
  fetchDataByGenre();
});
onMounted(() => {
  getGoodsList();
  getHottestGoodsList();
  fetchGenres();
});

const goods = ref<{ value: string }[]>([]);
const querySearch = async (queryString: string, cb: (list: { value: string }[]) => void) => {
  if (!queryString) return cb([]);
  try {
    const response = await searchGoodsByName(queryString);
    // 后端返回的是纯字符串数组，直接映射为 { value: string } 格式
    goods.value = Array.isArray(response)
        ? response.map(name => ({value: name})) // 直接使用字符串
        : [];
    cb(goods.value);
  } catch (error) {
    console.error('搜索建议失败:', error);
    cb([]);
  }
};

// 根据数据结构调整参数类型
const handleSelect = (item: { value: string }) => {
  input.value = item.value;
};
//退出登录
const logout = () => {
  useUserStore().logout();
};
// 商品列表分页
const handleCurrentChange = (val: number) => {
  currentPage.value = val; // 更新当前页码
  getGoodsList();// 重新获取商品列表
  console.log(`current page: ${val}`)
}
//搜索结果分页
const handleCurrentChange1 = (val: number) => {
  currentPage.value = val; // 更新当前页码
  searchData();// 重新获取商品列表
  console.log(`current page: ${val}`)
}
//商品类型分页
const handleCurrentChange2 = (val: number) => {
  currentPage.value = val; // 更新当前页码
  fetchDataByGenre();// 重新获取商品列表
  console.log(`current page: ${val}`)
}
//跳转到购物车
const handleCart = () => {
  if (userInfo && userInfo.id) {
    authStore.active = 0;
    router.push('/orderPublic');
  } else {
    alert('请先登录！')
  }
};
// 处理账户链接点击事件
const handleAccountClick = () => {
  if (userInfo && userInfo.id) {
    window.location.href = `/myAccount/${userInfo.id}`
  } else {
    alert('请先登录！')
  }
}
// 处理订单链接点击事件
const handleOrderClick = () => {
  if (userInfo && userInfo.id) {
    window.location.href = `/myOrder/${userInfo.id}`
  } else {
    alert('请先登录！')
  }
}
const router = useRouter();
// 切换登录/注册状态
const handleAuthSwitch = (mode: 'login' | 'register') => {
  // 1. 切换登录/注册状态
  if (mode === 'login') {
    authStore.switchToLogin();
  } else {
    authStore.switchToRegister();
  }

  // 2. 导航到目标路由（无刷新）
  router.replace('/login-register');
};
</script>
<template>
  <div class="app">
    <!-- Header -->
    <div class="header">
      <h1 class="logo">嗨购网上商城</h1>
      <div style="width: 40%;height: 100%">
        <ul class="shortcut">
          <li><a href="#" @click.prevent="handleAccountClick">我的账户</a></li>
          <li><a href="#" @click.prevent="handleOrderClick">我的订单</a></li>
          <li><a href="">使用帮助</a></li>
        </ul>
        <p class="logoInfo">
        <span style="display: flex;align-items: center;" v-if="isLogin">
          <el-avatar size="15" :src="userInfo.avatar"
                     style="margin-right: 10px;border: 1px solid #ccc;"/>
          <button @click="logout">退出</button>
        </span>
          <span class="login-register-links" v-if="!isLogin">
          [<a href="#" @click.prevent="handleAuthSwitch('login')">登录</a>
           <a href="#" @click.prevent="handleAuthSwitch('register')">注册</a>]
          </span>
        </p>
      </div>
    </div>
    <!-- Search -->
    <div class="search-container">
      <el-autocomplete v-model="input" placeholder="请输入" :fetch-suggestions="querySearch"
                       @select="handleSelect" clearable size="large"
                       style="width: 300px;height: 60%;margin: 0 20px">
        <template #prepend>
          <el-button @click="searchData">
            <el-icon>
              <Search/>
            </el-icon>
          </el-button>
        </template>
      </el-autocomplete>
      <el-select v-model="value" placeholder="请选择商品类型" clearable size="large"
                 @clear="handleClear"
                 style="width: 200px;margin:0 20px">
        <el-option v-for="item in cities" :key="item.value" :label="item.label"
                   :value="item.value"/>
      </el-select>

      <div class="cart-container" @click="handleCart">

          <el-icon class="cart-icon">
            <ShoppingCart/>
          </el-icon>
        <el-badge v-if="cartStore.cartStore.length" :value="cartStore.cartStore.length" :offset="[4, -5]">
          <span class="cart-text">购物车</span>
        </el-badge>
        <span v-else class="cart-text">购物车</span>
      </div>

    </div>
    <!-- Main Content -->
    <div class="main-content">
      <!-- All Products -->
      <div class="all-products-container-container">
        <div class="all-products-container">
          <el-card shadow="hover" v-for="product in goodsList" :key="product.id">
            <a :href="`/product/${product.id}`" style="text-decoration: none;">
              <img :src="product.image" alt="" style="width: 100%;aspect-ratio: 4/4;"/>
              <el-text class="product-name" truncated>
                {{ product.name }}
              </el-text>
              <div class="sale_price">惊喜价：¥{{ product.sale_price }}</div>
              <div class="market_price">市场价：<s>¥{{ product.market_price }}</s></div>
            </a>
          </el-card>
        </div>
        <!-- 分页组件 -->
        <!-- 搜索结果分页 -->
        <div class="demo-pagination-block" v-if="input.trim() !== ''">
          <el-pagination
              v-model:current-page="currentPage1"
              v-model:page-size="pageSize"
              size="large"
              background
              layout="prev, pager, next, jumper"
              :total="total1"
              hide-on-single-page
              @current-change="handleCurrentChange1"
          />
        </div>
        <!-- 商品类型分页 -->
        <div class="demo-pagination-block" v-else-if="value.trim() !== ''">
          <el-pagination
              v-model:current-page="currentPage2"
              v-model:page-size="pageSize"
              size="large"
              background
              layout="prev, pager, next, jumper"
              :total="total2"
              hide-on-single-page
              @current-change="handleCurrentChange2"
          />
        </div>
        <!-- 商品列表分页 -->
        <div v-else class="demo-pagination-block">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              size="large"
              background
              layout="prev, pager, next, jumper"
              :total="total"
              hide-on-single-page
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <!-- Hot Products -->
      <div class="hot-products-container">
        <span
            style="width: 100%;text-align: center;font-size: 20px;font-weight: bold;border-bottom: 1px solid #cccccc;">热销商品</span>
        <el-card shadow="hover" v-for="product in hottestGoodsList" :key="product.id">
          <a :href="`/product/${product.id}`" target="_blank" style="text-decoration: none;">
            <img :src="product.image" alt="" style="width: 100%;aspect-ratio: 4/4;"/>
            <el-text style="font-size: 12px;" truncated>
              {{ product.name }}
            </el-text>
            <div class="sale_price">¥{{ product.sale_price }}</div>
          </a>
        </el-card>
      </div>
    </div>
    <!-- Footer -->
    <div class="footer">
      <p class="links">
        <a href="">关于我们</a> |
        <a href="">常见问题</a> |
        <a href="">安全交易</a> |
        <a href="">购买流程</a> |
        <a href="">如何付款</a> |
        <a href="">联系我们</a> |
        <a href="">合作提案</a>
      </p>
      <p>Copyright 蜗牛学苑© 2015-2024 <a href="">蜀ICP备01000010号</a></p>
    </div>
  </div>
</template>
<style scoped>
.cart-container {
  margin-left: auto;
  margin-right: 20px;
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-radius: 20px;
  background: bisque;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
  font-size: 16px;
  gap: 8px;
}

.cart-icon {
  font-size: 25px;
  color: orange;
}

.cart-text {
  font-weight: bold;
  color: #303133;
  margin-left: 4px;
}

.cart-container:hover {
  background: #c0e3ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.cart-container:active {
  transform: translateY(0);
}

.demo-pagination-block {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  margin: 30px auto;
}

.main-content {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start; /* 关键：让子元素高度独立 */
}

.all-products-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  border: 1px solid #cccccc;
  width: 100%;
}

.all-products-container-container {
  display: flex;
  flex-direction: column;
  width: 80%;
}

.all-products-container .el-card {
  display: flex;
  flex-direction: column;
  width: 19.5%;
  margin: 5px 0.15%;
}

.product-name {
  width: 100%;
  font-size: 16px;
}

.sale_price {
  color: #f67373;
}

.market_price {
  color: #758291;
}

.hot-products-container {
  border: 1px solid #cccccc;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 20%;
  max-height: 895px;
  overflow-y: auto;
}

.hot-products-container::-webkit-scrollbar {
  width: 2px;
}

.hot-products-container::-webkit-scrollbar-thumb {
  background-color: #696969;
}

.hot-products-container .el-card {
  text-align: center;
  display: flex;
  flex-direction: column;
  width: 49%;
  margin: 3px 0;
}

:deep( .hot-products-container .el-card__body) {
  padding: 10px !important; /* 强制应用样式 */
}

.search-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  height: 70px;
}

/* Footer */
.footer {
  padding: 20px 0;
  text-align: center;
  color: #666;
}

.footer .links {
  margin-bottom: 10px;
}

.footer a {
  text-decoration: none;
  color: #666;
  margin: 0 5px;
}

.header {
  display: flex;
  flex-direction: row;
  width: 100%;
}

.logo {
  padding-left: 30px;
  width: 60%;
  color: orange;
  line-height: 60px;
  font-weight: 500;
  font-style: italic;
  letter-spacing: 5px;
}

.login-register-links {
  margin-left: 15px;
}

.login-register-links a {
  color: #e17d58;
  text-decoration: none;
  margin: 0 5px;
}

.shortcut {
  display: flex;
  list-style: none;
  justify-content: right;
  margin-right: 20px;
}

.shortcut li {
  margin-left: 15px;
}

.shortcut a {
  text-decoration: none;
  color: #666;
}

.logoInfo {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: right;
  padding-right: 20px;
}
</style>
